package com.sharding.sphere.demo.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;

/**
 * @author: shuguang.zhang
 * @date : 2021-06-04 15:16
 */
@Slf4j
public class TradeOrderTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> tablesName, PreciseShardingValue<Long> preciseShardingValue) {

        log.info("TradeOrderTablePreciseShardingAlgorithm ---> tablesName:[{}] complexKeysShardingValue:[{}]", tablesName, preciseShardingValue);

        // 逻辑表名
        String logicTableName = preciseShardingValue.getLogicTableName();

        // 分片的字段值
        Long value = preciseShardingValue.getValue();

        // 分片的字段名
        String columnName = preciseShardingValue.getColumnName();

        BigInteger shardingValue = BigInteger.valueOf(value).mod(new BigInteger("2")).add(BigInteger.ONE);
        String key = logicTableName.concat("_")+shardingValue;

        if (tablesName.contains(key)) {
            return key;
        }

        throw new UnsupportedOperationException("");
    }
}
